<?php

namespace app\adminapi\controller\setting;

use app\adminapi\controller\Base;
use app\adminapi\controller\plugin\LoginManager;
use app\common\plugin\MainApiService;

class Marketplace extends Base
{
    /**
     * Get plugin market configuration
     */
    public function getConfig()
    {
        try {
            $siteConfig       = config('site');
            $marketplaceLogin = $this->getMarketplaceLoginStatus();

            $data = [
                'config' => [
                    'main_api_url' => $siteConfig['marketplace']['main_api_url'] ?? '',
                ],
                'login'  => $marketplaceLogin
            ];
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $data);
    }

    /**
     * Save plugin market configuration
     */
    public function saveConfig()
    {
        try {
            $mainApiUrl = $this->request->post('main_api_url', '');

            // Read the current configuration
            $configFile = config_path() . '/site.php';
            $config     = require $configFile;

            // Update plugin market configuration
            $config['marketplace']['main_api_url'] = $mainApiUrl;

            // Write back to the configuration file
            $content = "<?php\nreturn " . $this->formatArrayAsPhp($config) . ";\n";
            file_put_contents($configFile, $content);

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Login to plugin market - reuse Auth controller logic
     */
    public function login()
    {
        $email    = $this->request->post('username');
        $password = $this->request->post('password');

        if (empty($email)) {
            return $this->error(trans('email_cannot_be_empty'));
        }

        if (empty($password)) {
            return $this->error(trans('password_cannot_be_empty'));
        }

        $mainApiService = new MainApiService();
        // Call the login interface of the main project
        $loginResult = $mainApiService->login($email, $password);

        // Login successfully, save to cache file
        $loginManager = new LoginManager();
        $token        = $loginManager->saveLogin($email, $loginResult['token'], $loginResult['user']);

        return $this->success('', [
            'token'     => $token,
            'user_info' => $loginResult['user'],
            'email'     => $email
        ]);
    }

    /**
     * Logout - reuse Auth controller logic
     */
    public function logout()
    {
        // Reuse Auth controller logout logic
        $authController = new \app\adminapi\controller\plugin\Auth();

        // Call Auth's logout method
        $result = $authController->logout();

        return $result;
    }

    /**
     * Get login status - reuse Auth controller logic
     */
    public function getLoginStatus()
    {
        // Reuse Auth controller check login logic
        $authController = new \app\adminapi\controller\plugin\Auth();

        // Call Auth's check login method
        $result = $authController->checkLogin();

        return $result;
    }

    /**
     * Get plugin market login status
     */
    private function getMarketplaceLoginStatus()
    {
        $cacheFile = runtime_path() . '/plugin_cache/market_login.json';

        if (file_exists($cacheFile)) {
            $data = json_decode(file_get_contents($cacheFile), true);
            if ($data) {
                // Check if expired
                $isExpired = false;
                if (isset($data['expire_time']) && $data['expire_time'] < time()) {
                    $isExpired = true;
                }

                return [
                    'isLoggedIn' => !$isExpired,
                    'userInfo'   => [
                        'id'        => $data['user_info']['id'] ?? null,
                        'name'      => $data['user_info']['name'] ?? null,
                        'email'     => $data['user_info']['email'] ?? null,
                        'avatar'    => $data['user_info']['avatar'] ?? null,
                        'vip_level' => $data['user_info']['vip_level'] ?? 0,
                    ],
                    'loginTime'  => $data['login_time'] ?? null,
                    'expireTime' => $data['expire_time'] ?? null,
                    'isExpired'  => $isExpired,
                ];
            }
        }

        return [
            'isLoggedIn' => false,
            'userInfo'   => null,
            'loginTime'  => null,
            'expireTime' => null,
            'isExpired'  => false,
        ];
    }

    /**
     * Format array as PHP code
     */
    private function formatArrayAsPhp($array, $indent = 0)
    {
        if (!is_array($array)) {
            return var_export($array, true);
        }

        $spaces     = str_repeat('    ', $indent);
        $nextSpaces = str_repeat('    ', $indent + 1);

        // Check if it is an indexed array
        $isIndexed = array_keys($array) === range(0, count($array) - 1);

        $result = "[\n";

        foreach ($array as $key => $value) {
            $result .= $nextSpaces;

            // If it is not an indexed array, add the key
            if (!$isIndexed) {
                $result .= var_export($key, true) . ' => ';
            }

            // Recursively process the value
            if (is_array($value)) {
                $result .= $this->formatArrayAsPhp($value, $indent + 1);
            } else {
                $result .= var_export($value, true);
            }

            $result .= ",\n";
        }

        $result .= $spaces . ']';

        return $result;
    }
}
